import BaseAction from '@/components/base/BaseAction';
import BaseButton from '@/components/base/BaseButton';
import { useModal } from '@/components/base/BaseModal';
import BasePageFrame from '@/components/base/BasePageFrame';
import BaseSelect from '@/components/base/BaseSelect';
import BaseTable from '@/components/base/BaseTable';
import { getList as getRadarList, getRadarTreeListByRadarId } from '@/pages/radar/RadarInfo/api';
import { EnumValueType } from '@/utils/enum';
import { useRequest } from '@/utils/request';
import {
  DeleteOutlined,
  EditOutlined,
  ExportOutlined,
  FileTextOutlined,
  PlusOutlined,
  ToolOutlined
} from '@ant-design/icons';
import { ActionType, ProColumns } from '@ant-design/pro-table';
import { Cascader, DatePicker, Radio, Space, Tag } from 'antd';
import moment from 'moment';
import { useRef, useState } from 'react';
import { FaultProcessStateEnum, FaultRecordModel, FaultSourceEnum } from '../data';
import DealModal from '../RepairRecord/modals/DealModal';
import { delInfo, exportExecl, getList } from './api';
import InfoModal from './modals/InfoModal';
import LoadFaultPhenomenonModal from './modals/LoadFaultPhenomenonModal';

const Info = () => {
  const tableRef = useRef<ActionType>();
  const loadFaultPhenomenonModal = useModal(LoadFaultPhenomenonModal);
  const infoModal = useModal(InfoModal, {
    onSuccess() {
      // console.log(id);
      // if (id) {
      //   loadFaultPhenomenonModal.load({ radarTypeId recordId: id, allowEdit: true });
      // }
      tableRef.current?.reload();
    }
  });
  const dealModal = useModal(DealModal, {
    onSuccess() {
      tableRef.current?.reload();
    }
  });
  const del = useRequest(delInfo, {
    manual: true,
    fetchKey: (id) => id,
    onSuccess() {
      tableRef.current?.reload();
    }
  });
  const [searchInfo, setSearchInfo] = useState<{
    downTimeStart?: string;
    downTimeEnd?: string;
    isDeal?: EnumValueType<typeof FaultProcessStateEnum.enum> | undefined;
    radarId?: string;
    systemId?: string;
    extensionId?: string;
    keyPartsModelId?: string;
  }>({});

  const radarTree = useRequest(getRadarTreeListByRadarId, {
    manual: true
  });
  return (
    <BasePageFrame>
      <BaseTable
        rowKey='id'
        actionRef={tableRef}
        headerTitle={
          <Space>
            <BaseSelect
              request={getRadarList}
              allowClear
              fieldNames={{ label: 'name', value: 'id' }}
              onChange={(radarId) => {
                if (radarId) {
                  radarTree.run(radarId);
                } else {
                  radarTree.mutate([]);
                }
                setSearchInfo({
                  ...searchInfo,
                  radarId,
                  systemId: undefined,
                  extensionId: undefined,
                  keyPartsModelId: undefined
                });
              }}
              placeholder='请选择雷达'
              style={{ width: 180 }}
            />
            <Cascader
              fieldNames={{ label: 'name', value: 'id' }}
              changeOnSelect
              allowClear
              value={
                [searchInfo.systemId, searchInfo.extensionId, searchInfo.keyPartsModelId].filter(
                  (i) => i
                ) as string[]
              }
              placeholder='请选择需要查询的雷达结构'
              style={{ width: 500 }}
              options={radarTree.data ? radarTree.data[0]?.children ?? [] : []}
              onChange={(value) => {
                const [systemId, extensionId, keyPartsModelId] = value as string[];
                setSearchInfo({
                  ...searchInfo,
                  systemId,
                  extensionId,
                  keyPartsModelId
                });
              }}
            />
            <DatePicker.RangePicker
              placeholder={['请选择故障时间段', '请选择故障时间段']}
              showTime={{ format: 'HH:mm:ss' }}
              format='YYYY-MM-DD HH:mm:ss'
              ranges={{
                今天: [moment().startOf('day'), moment().endOf('day')],
                本月: [moment().startOf('month'), moment().endOf('month')]
              }}
              onChange={(values, dateStrings) => {
                const [downTimeStart, downTimeEnd] = dateStrings;
                setSearchInfo({
                  ...searchInfo,
                  downTimeStart,
                  downTimeEnd
                });
              }}
            />
            <Radio.Group
              defaultValue={searchInfo.isDeal}
              optionType='button'
              options={[{ label: '全部', value: undefined as any }, ...FaultProcessStateEnum.list]}
              onChange={(e) => {
                setSearchInfo({
                  ...searchInfo,
                  isDeal: e.target.value
                });
              }}
            />
          </Space>
        }
        toolBarRender={() => [
          <BaseButton
            code='create'
            type='primary'
            icon={<PlusOutlined />}
            onClick={() => {
              infoModal.load({});
            }}
          >
            新增
          </BaseButton>,
          <BaseButton
            type='primary'
            icon={<ExportOutlined />}
            onClick={() => {
              exportExecl(searchInfo);
            }}
          >
            导出
          </BaseButton>
        ]}
        params={searchInfo}
        request={getList}
        columns={
          [
            {
              dataIndex: 'raEquipmentNames',
              title: '故障设备'
            },
            {
              dataIndex: 'faultResource',
              title: '故障来源',
              renderText: FaultSourceEnum.getLabelByValue
            },
            {
              dataIndex: 'downTime',
              title: '故障时间',
              valueType: 'dateTime'
            },
            {
              dataIndex: 'isDeal',
              title: '处理状态',
              render: (text, record) => {
                const t = FaultProcessStateEnum.getLabelByValue(record.isDeal);
                const color = record.isDeal ? 'success' : 'warning';
                return t && <Tag color={color}>{t}</Tag>;
              }
            },
            {
              dataIndex: 'remarks',
              title: '故障描述'
            },
            {
              dataIndex: '',
              title: '操作',
              fixed: 'right',
              render(text, record) {
                return (
                  <Space>
                    {!record.isDeal && (
                      <BaseAction
                        color='blue'
                        icon={<ToolOutlined />}
                        title='维修'
                        code='service'
                        onClick={() => {
                          dealModal.load({ faultRecordId: record.id, faultTime: record.downTime });
                        }}
                      />
                    )}
                    <BaseAction
                      color='blue'
                      icon={<FileTextOutlined />}
                      title='故障现象'
                      code='loadFP'
                      onClick={() => {
                        loadFaultPhenomenonModal.load({
                          radarTypeId: record.radarTypeId,
                          recordId: record.id,
                          allowEdit: !record.isDeal
                        });
                      }}
                    />
                    {!record.isDeal && record.faultResource === FaultSourceEnum.enum.manual ? (
                      <>
                        <BaseAction
                          color='green'
                          icon={<EditOutlined />}
                          title='编辑'
                          code='edit'
                          onClick={() => {
                            infoModal.load({ data: record });
                          }}
                        />
                        <BaseAction
                          color='red'
                          icon={<DeleteOutlined />}
                          title='删除'
                          code='delete'
                          loading={del.fetches[record.id]?.loading}
                          onClick={() => {
                            del.run(record.id);
                          }}
                        />
                      </>
                    ) : null}
                  </Space>
                );
              }
            }
          ] as ProColumns<FaultRecordModel>[]
        }
      />
    </BasePageFrame>
  );
};

export default Info;
